package com.taysear.dbservice.resources;

import java.io.StringWriter;

import java.sql.ResultSet;
import java.sql.ResultSetMetaData;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Document;
import org.w3c.dom.Element;

/**
 * Converters given data into XML.
 * 
 * @author Abdullahi
 * 
 */
public class XmlConverter {
	static String rowName = "ROW";
	static String tableName = "RESULTS";
	//static String sizeName = "SIZE";
	//static String rowCountIdName = "ROWCOUNTID";

	/**
	 * Returns a xml string consists the records.
	 * <p>
	 * This method is a static one, so that it is invoked directly using the
	 * classname.
	 * 
	 * @param ResultSet
	 *            Set of Records to be converted into xml format
	 * @return the xml string
	 */
	public static String getXmlData(ResultSet resultSet) throws Exception {
		DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
		DocumentBuilder builder = factory.newDocumentBuilder();
		Document doc = builder.newDocument();
		Element results = doc.createElement(tableName);
		doc.appendChild(results);

		ResultSetMetaData resultSetMetaData = resultSet.getMetaData();
		int colCount = resultSetMetaData.getColumnCount();

		int vRowCount = 0;
		while (resultSet.next()) {
			vRowCount++;
			Element row = doc.createElement(rowName);
			//row.setAttribute(rowCountIdName, Integer.toString(vRowCount));
			results.appendChild(row);
			for (int i = 1; i <= colCount; i++) {
				String columnName = resultSetMetaData.getColumnLabel(i);
				Object value = null;
				try {
					value = resultSet.getObject(i);
					if (value == null)
						throw new NullPointerException();
				} catch (NullPointerException e) {
					value = "";
				} catch (Exception e) {
					value = "";
				}
				Element node = doc.createElement(columnName);
				node.appendChild(doc.createTextNode(value.toString()));
				row.appendChild(node);
			}
		}
		//results.setAttribute(sizeName, Integer.toString(vRowCount));

		DOMSource domSource = new DOMSource(doc);
		TransformerFactory tf = TransformerFactory.newInstance();
		Transformer transformer = tf.newTransformer();
		transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
		transformer.setOutputProperty(OutputKeys.METHOD, "xml");
		transformer.setOutputProperty(OutputKeys.ENCODING, "ISO-8859-1");
		StringWriter sw = new StringWriter();
		StreamResult sr = new StreamResult(sw);
		transformer.transform(domSource, sr);

		return sw.toString();

	}
}
